package controller_user

import (
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"strings"
	"tools-api/src/common/utils"
	"tools-api/src/jcj/model"
	"tools-api/src/jcj/service/service_user"
	"tools-api/src/routes/request"
	"tools-api/src/routes/response"
)

func Register(ctx *gin.Context) {
	// 1. 注册 使用用户JID utils.GenerateJID()
	// 2. MFA 密钥生成、重置功能
	// 3. 拷贝默认类别
	// 4. 创建默认账本
}

func Login(ctx *gin.Context) {
	var req struct {
		Phone    string `json:"phone"`
		Password string `json:"password"`
		MfaCode  string `json:"mfa_code"`
		Cate     int    `json:"cate"` // MFA是否校验 0-不校验 1-校验
	}
	_ = ctx.ShouldBindBodyWith(&req, binding.JSON)
	if len(req.Phone) != 11 || len(req.Password) == 0 || len(req.Password) > 32 {
		response.Fail(ctx, "手机号或密码错误")
		return
	}
	if req.Cate == 1 && strings.TrimSpace(req.MfaCode) == "" {
		response.Fail(ctx, "验证码不能为空")
		return
	}
	user := model.User{}.Verify(req.Phone, req.Password)
	if user.Id <= 0 {
		response.Fail(ctx, "手机号或密码错误")
		return
	}
	// 2. 检查用户是否启用 MFA（从数据库查询）
	next := false
	if user.MfaEnabled == 1 {
		if req.Cate == 1 {
			// 校验MFA
			if !utils.MFAVerify(user.MfaSecret, req.MfaCode) {
				response.Fail(ctx, "验证码错误")
				return
			}
			next = true
		} else {
			response.FailByCode(ctx, response.MFARequired, "") // 要求客户端输入校验MFA
		}
	} else {
		next = true
	}
	if !next {
		return
	}
	// 生成登录日志 需要先生成才有tokenVersion
	tokenVersion, err := model.UserLoginRecord{}.Create(user.Uuid, request.GetDeviceType(ctx), request.GetDeviceId(ctx), request.GetClientIP(ctx))
	if err != nil {
		response.Fail(ctx, "登录失败")
		return
	}
	// 生成TOKEN AccessToken当天有效 + RefreshToken打开app7天后实效 机制
	refreshToken, err2 := service_user.RefreshTokenGenerate(user.Uuid, tokenVersion)
	if err2 != nil {
		response.Fail(ctx, "登录失败")
		return
	}
	accessToken, err3 := service_user.AccessTokenGenerate(user.Uuid, tokenVersion)
	if err3 != nil {
		response.Fail(ctx, "登录失败")
		return
	}
	info := getUserInfo(user) // 获取用户信息
	response.SuccessItems2Msg(ctx, gin.H{
		"access_token":  accessToken,
		"refresh_token": refreshToken,
		"info":          info,
	}, "登录成功")
}

// Logout 退出登录
func Logout(ctx *gin.Context) {
	err := model.UserLoginRecord{}.IncreaseTokenVersion(request.GetCurrentUser(ctx), request.GetDeviceType(ctx), request.GetDeviceId(ctx))
	if err != nil {
		response.Fail(ctx, "退出失败，稍后再试")
		return
	}
	response.SuccessMsg(ctx, "退出成功")
}
